package com.jingdianjichi.club.gateway.filter;


import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: 网关的全局拦截器---登录拦截器---解析token，获取用户openId
 * @return:
 * @Author:  sky
 * @date:  2024/11/23 22:30
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter {

    @Override
    @SneakyThrows
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取前端请求
        ServerHttpRequest request = exchange.getRequest();
        // 获取前端请求的改变builder（包括全部内容）
        ServerHttpRequest.Builder mutate = request.mutate();
        String url = request.getURI().getPath();
        if(log.isInfoEnabled()){
            log.info("LoginFilter.filter.url:{}",url);
        }
        // 放行特定的请求路径 (未登录)
        if(url.equals("/auth/user/doLogin")){
            chain.filter(exchange);
        }
        // sa-token获取token信息，获取loginId
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String loginId = (String) tokenInfo.getLoginId();
        if(StringUtils.isEmpty(loginId)){
            throw new Exception("未获取到用户信息");
        }
        // 将解析的loginId填充到请求包的header里
        mutate.header("loginId",loginId);
        // build新的请求
        // exchange.mutate()返回一个builder
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}
